﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.IO;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

namespace Framework.WebmasterTool
{
    public partial class VideoClips : System.Web.UI.Page
    {
        static string[] videoExtensions = new string[5] { "flv", "avi", "swf", "mpg", "mp4" };

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "AddedDate" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }

        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Descending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (rdbUploadFile.Checked == true)
            {
                //txtURLVideo.Enabled = false;
                txtURLVideo.ReadOnly = true;
                fuVideo.Enabled = true;
                RegularExpressionValidator1.Visible = false;
            }
            else
            {
                //txtURLVideo.Enabled = true;
                txtURLVideo.ReadOnly = false;
                fuVideo.Enabled = false;
                RegularExpressionValidator1.Visible = true;
            }
            if (!IsPostBack)
            {
                CheckPermission();
                //CleanImageUploadTemp();
                CallImageUpload();
                LoadCateDDL();
                LoadVideos();
                if (Request.QueryString["ClipID"] != null)
                {
                    int clipID = 0;
                    int.TryParse(Request.QueryString["ClipID"].ToString(), out clipID);
                    LoadVideoDetails(clipID);
                }
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.GalleryVideo.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void CallImageUpload()
        {
            ImageUpload(siuImage);
        }

        public void LoadCateDDL()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            List<udv_Categories> cateBannerParent = allCate.Where(ca => ca.ParentID == ConfigPaths.Category_Video_ID).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                ddlCategories2.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        public void LoadSubCateDDL(ref List<udv_Categories> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                ddlCategories2.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public void LoadVideos()
        {
            var source = entity.udv_Videos.Include("udv_Categories").Select(vd => new { vd.VideoID, vd.Title, vd.Title_en, CateName = vd.udv_Categories.Title, CateID = vd.udv_Categories.CateID, vd.AddedDate, vd.IsActive, vd.DisplayOrder }).OrderBy(fi => fi.DisplayOrder).ThenByDescending(fi => fi.AddedDate).ToList();
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                source = source.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                source = source.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvVideoClip.DataSource = source;
            grvVideoClip.DataBind();
        }

        public void SetMedia(string videoUrl, bool UploadVideo)
        {
            if (UploadVideo == true)
            {
                divMediaPlayer.InnerHtml = "<embed id='MediaPlayer' allowfullscreen='true' allowscriptaccess='always'"
                            + "flashvars='width=350&amp;height=300&amp;file=" + ConfigPaths.Path_Videos_Folder.Substring(1) + videoUrl + "&amp;backcolor=000000&amp;frontcolor=FFFFFF&amp;lightcolor=00FF00&amp;screencolor=000000&amp;autostart=true'"
                            + "height='300' name='MediaPlayer' quality='high' src='../Plugins/JwPlayer/player.swf' style=''"
                            + "type='application/x-shockwave-flash' width='350' wmode='opaque'></embed>";
            }
            else
            {
                divMediaPlayer.InnerHtml = "<embed id='MediaPlayer' allowfullscreen='true' allowscriptaccess='always'"
                            + "flashvars='width=350&amp;height=300&amp;file=" + videoUrl + "&amp;backcolor=000000&amp;frontcolor=FFFFFF&amp;lightcolor=00FF00&amp;screencolor=000000&amp;autostart=true'"
                            + "height='300' name='MediaPlayer' quality='high' src='../Plugins/JwPlayer/player.swf' style=''"
                            + "type='application/x-shockwave-flash' width='350' wmode='opaque'></embed>";
            }
        }

        public void LoadVideoDetails(int videoID)
        {
            var video = entity.udv_Videos.Where(vd => vd.VideoID == videoID).FirstOrDefault();

            if (video != null)
            {
                video.udv_CategoriesReference.Load();
                txtTitleVideo.Text = video.Title.Trim();
                txtTitleVideo_en.Text = video.Title_en.Trim();
                ddlCategories.SelectedValue = video.udv_Categories.CateID.ToString();
                lblAddedDate.Text = String.Format("{0:dd/MM/yyyy}", video.AddedDate);
                lblAddedBy.Text = video.AddedBy.Trim();
                lblUpdatedDate.Text = String.Format("{0:dd/MM/yyyy}", video.UpdatedDate);
                lblUpdatedBy.Text = video.UpdatedBy.Trim();
                lblTotalViews.Text = video.TotalViews.ToString();
                lblTotalRating.Text = video.TotalRating.ToString();
                txtDescription.Text = video.Description;
                txtDescription_en.Text = video.Description_en;
                txtSummary.Text = video.Summary;
                txtSummary_en.Text = video.Summary_en;
                txtMetaDescription.Text = video.MetaDescription.Trim();
                txtMetaKeywords.Text = video.MetaKeywords.Trim();
                chkIsActive.Checked = video.IsActive.Value;
                chkTop.Checked = video.IsTop.Value;
                chkCommentsEnable.Checked = video.CommentsEnable.Value;
                chkApprovedComments.Checked = video.ApprovedComments.Value;
                chkOnlyForMember.Checked = video.OnlyForMember.Value;
                txtDisplayOrder.Text = video.DisplayOrder.ToString();
                SetMedia(video.FileURL, video.FileType.Contains("video"));
                btnDeleteVideo.Visible = btnCancel.Visible = true;
                if (video.ImageUrl != null && video.ImageUrl.Trim() != "")
                {
                    string sourceImageFilePath = ConfigPaths.Path_Videos_Folder_MapPath + video.ImageUrl;
                    siuImage.LoadImageFromFileSystem(Server.MapPath(sourceImageFilePath));
                }
                if (video.FileType.Contains("video"))
                {
                    rdbUploadFile.Checked = true;
                    rdbUploadURL.Checked = false;
                    txtURLVideo.Text = ConfigPaths.Path_Videos_Folder.Substring(1) + video.FileURL;
                }
                else
                {
                    rdbUploadURL.Checked = true;
                    rdbUploadFile.Checked = false;
                    txtURLVideo.Text = video.FileURL;
                }
                btnSave.CommandName = "update";
                btnSave.CommandArgument = btnDeleteVideo.CommandArgument = video.VideoID.ToString();
                if (rdbUploadFile.Checked == true)
                {
                    //txtURLVideo.Enabled = false;
                    txtURLVideo.ReadOnly = true;
                    fuVideo.Enabled = true;
                }
                else
                {
                    //txtURLVideo.Enabled = true;
                    txtURLVideo.ReadOnly = false;
                    fuVideo.Enabled = false;
                }
            }
            else
            {
                Response.Redirect("VideoClips.aspx");
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            int cateID = 0;
            try
            {
                cateID = int.Parse(ddlCategories.SelectedValue);
            }
            catch
            {
                lblMsg.Text = "Chưa chọn danh mục cho video";
            }
            if (btnSave.CommandName == "Insert")
            {
                udv_Videos video = new udv_Videos();
                video.Title = txtTitleVideo.Text.Trim();
                video.Title_en = txtTitleVideo_en.Text.Trim();
                if (ddlCategories.SelectedValue.Trim() != "0")
                {
                    video.udv_Categories = entity.udv_Categories.Where(ca => ca.CateID == cateID).FirstOrDefault();
                }
                video.AddedDate = DateTime.Now;
                video.AddedBy = Membership.GetUser().UserName;
                video.UpdatedDate = DateTime.Now;
                video.UpdatedBy = Membership.GetUser().UserName;
                video.TotalViews = 0;
                video.TotalRating = 0;
                video.Description = txtDescription.Text;
                video.Description_en = txtDescription_en.Text;
                video.Summary = txtSummary.Text;
                video.Summary_en = txtSummary_en.Text;
                video.MetaDescription = txtMetaDescription.Text.Trim();
                video.MetaKeywords = txtMetaKeywords.Text.Trim();
                video.IsActive = chkIsActive.Checked;
                video.IsTop = chkTop.Checked;
                video.CommentsEnable = chkCommentsEnable.Checked;
                video.ApprovedComments = chkApprovedComments.Checked;
                video.OnlyForMember = chkOnlyForMember.Checked;
                video.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                if (siuImage.HasImage == true)
                {
                    string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                    siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_Videos_Folder + fileNameImage);
                    video.ImageUrl = fileNameImage;
                }
                else
                {
                    video.ImageUrl = "";
                }
                if (fuVideo.HasFile)
                {
                    string videoUploadName = Globals.GetFileName(Globals.RemoveSign4VietnameseString(fuVideo.FileName));
                    if (!videoExtensions.Any(ve => System.IO.Path.GetExtension(videoUploadName).ToLower().Contains(ve)))
                    {
                        lblMsg.Visible = true;
                        lblMsg.Text = "Video upload không hợp lệ, video phải là flv, avi, swf, mpg, mp4";
                        return;
                    }
                    if (fuVideo.PostedFile.ContentLength > 51000000)
                    {
                        lblMsg.Visible = true;
                        lblMsg.Text = "Video có dung lượng quá lớn, dung lượng phải nhỏ hơn 50M";
                        return;
                    }
                    else
                    {
                        video.FileURL = videoUploadName;
                        video.FileType = fuVideo.PostedFile.ContentType + " | " + System.IO.Path.GetExtension(fuVideo.FileName).Substring(1) + " | video";
                        video.FileSize = fuVideo.PostedFile.ContentLength / 1024;
                        fuVideo.SaveAs(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + videoUploadName));
                    }
                }
                else if (txtURLVideo.ReadOnly == false)
                {
                    if (txtURLVideo.Text.Trim() == "")
                    {
                        lblMsg.Text = "Chưa nhập URL cho video";
                        return;
                    }
                    else
                    {
                        video.FileType = "";
                        video.FileSize = 0;
                        video.FileURL = txtURLVideo.Text.Trim();
                    }
                }
                entity.AddToudv_Videos(video);
                entity.SaveChanges();
                string urlRewriteVideo = Globals.CreateUrlRewriteVideo(ref entity, video.VideoID, true);
                video.UrlRewrite = urlRewriteVideo;
                entity.SaveChanges();

                //create db log
                CreateDBLog(null, null, TypeAction.Insert, "Tạo video clip: " + video.Title, video.Description, "", "", "",
                        video.IsActive.Value.ToString(), video.IsTop.Value.ToString(), video.MetaKeywords, video.MetaDescription);

                Globals.CreateROR("~/ror.xml", urlRewriteVideo + DGSFramework.Globals.GetUrlRewriteExtension(), video.Title, video.MetaDescription);
                Globals.CreateSiteMap("~/sitemap.xml", urlRewriteVideo + DGSFramework.Globals.GetUrlRewriteExtension());
                Globals.CreateUrlList("~/urllist.txt", urlRewriteVideo + DGSFramework.Globals.GetUrlRewriteExtension());
                Cache.Remove("Video");
                Response.Redirect("VideoClips.aspx");
            }
            else
            {
                int videoID = int.Parse(btnSave.CommandArgument);
                udv_Videos video = entity.udv_Videos.Where(vd => vd.VideoID == videoID).FirstOrDefault();
                string oldTitle = video.Title;
                video.Title = txtTitleVideo.Text.Trim();
                video.Title_en = txtTitleVideo_en.Text.Trim();
                string urlRewriteVideoOld = Globals.CreateUrlRewriteVideo(ref entity, video.VideoID, true);
                string urlRewriteVideoNew;
                if (ddlCategories.SelectedValue.Trim() != "0")
                {
                    video.udv_Categories = entity.udv_Categories.Where(ca => ca.CateID == cateID).FirstOrDefault();
                }
                video.AddedBy = Membership.GetUser().UserName;
                video.UpdatedDate = DateTime.Now;
                video.UpdatedBy = Membership.GetUser().UserName;
                video.Description = txtDescription.Text;
                video.Description_en = txtDescription_en.Text;
                video.Summary = txtSummary.Text;
                video.Summary_en = txtSummary_en.Text;
                video.MetaDescription = txtMetaDescription.Text.Trim();
                video.MetaKeywords = txtMetaKeywords.Text.Trim();
                video.IsActive = chkIsActive.Checked;
                video.IsTop = chkTop.Checked;
                video.CommentsEnable = chkCommentsEnable.Checked;
                video.ApprovedComments = chkApprovedComments.Checked;
                video.OnlyForMember = chkOnlyForMember.Checked;
                video.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                if (siuImage.HasNewImage == true)
                {
                    Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + video.ImageUrl));
                    string fileNameImage = Globals.GetFileName(siuImage.SourceImageClientFileName);
                    siuImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_Videos_Folder + fileNameImage);
                    video.ImageUrl = fileNameImage;
                }
                else if (siuImage.HasImage == false)
                {
                    Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder + video.ImageUrl));
                    video.ImageUrl = "";
                }
                if (fuVideo.HasFile)
                {
                    string videoUploadName = Globals.GetFileName(Globals.RemoveSign4VietnameseString(fuVideo.FileName));
                    if (!videoExtensions.Any(ve => System.IO.Path.GetExtension(videoUploadName).ToLower().Contains(ve)))
                    {
                        lblMsg.Visible = true;
                        lblMsg.Text = "Video upload không hợp lệ, video phải là flv, avi, swf, mpg, mp4";
                        return;
                    }
                    if (fuVideo.PostedFile.ContentLength > 51000000)
                    {
                        lblMsg.Visible = true;
                        lblMsg.Text = "Video có dung lượng quá lớn, dung lượng phải nhỏ hơn 50M";
                        return;
                    }
                    else
                    {
                        if (video.FileType.Contains("video"))
                        {
                            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + video.FileURL));
                        }
                        video.FileURL = videoUploadName;
                        video.FileType = fuVideo.PostedFile.ContentType + " | " + System.IO.Path.GetExtension(fuVideo.FileName).Substring(1) + " | video";
                        video.FileSize = fuVideo.PostedFile.ContentLength / 1024;
                        fuVideo.SaveAs(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + videoUploadName));
                    }
                }
                else if (txtURLVideo.ReadOnly == false)
                {
                    if (txtURLVideo.Text.Trim() == "")
                    {
                        lblMsg.Text = "Chưa nhập URL cho video";
                        return;
                    }
                    else
                    {
                        if (video.FileType.Contains("video"))
                        {
                            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + video.FileURL));
                        }
                        video.FileType = "";
                        video.FileSize = 0;
                        video.FileURL = txtURLVideo.Text.Trim();
                    }
                }
                entity.SaveChanges();
                urlRewriteVideoNew = Globals.CreateUrlRewriteVideo(ref entity, video.VideoID, true);
                video.UrlRewrite = urlRewriteVideoNew;
                entity.SaveChanges();

                //create db log
                CreateDBLog(null, null, TypeAction.Update, "Cập nhật video clip: " + oldTitle + " - " + video.Title, video.Description, "", "", "",
                        video.IsActive.Value.ToString(), video.IsTop.Value.ToString(), video.MetaKeywords, video.MetaDescription);

                Globals.UpdateROR("~/ror.xml", urlRewriteVideoOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteVideoNew + DGSFramework.Globals.GetUrlRewriteExtension(), video.Title, video.MetaDescription);
                Globals.UpdateSiteMap("~/sitemap.xml", urlRewriteVideoOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteVideoNew + DGSFramework.Globals.GetUrlRewriteExtension());
                Globals.UpdateUrlList("~/urllist.txt", urlRewriteVideoOld + DGSFramework.Globals.GetUrlRewriteExtension(), urlRewriteVideoNew + DGSFramework.Globals.GetUrlRewriteExtension());
                Cache.Remove("Video");
                Response.Redirect("VideoClips.aspx");
            }
        }

        protected void imbEdit_Command(object sender, CommandEventArgs e)
        {
            int clipID = int.Parse(e.CommandArgument.ToString());
            //SearchVideos();
            //LoadVideoDetails(clipID);
            //lblMsg.Visible = false;
            Response.Redirect("VideoClips.aspx?ClipID=" + clipID);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("VideoClips.aspx");
        }

        protected void btnDeleteVideo_Click(object sender, EventArgs e)
        {
            int videoID = int.Parse(btnDeleteVideo.CommandArgument.ToString());
            var video = entity.udv_Videos.Where(vd => vd.VideoID == videoID).FirstOrDefault();
            if (video.FileType.Contains("video"))
            {
                Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + video.FileURL));
            }
            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + video.ImageUrl));
            string urlRewriteVideoOld = Globals.CreateUrlRewriteVideo(ref entity, video.VideoID, true) + DGSFramework.Globals.GetUrlRewriteExtension();
            Globals.DeleteROR("~/ror.xml", urlRewriteVideoOld);
            Globals.DeleteSiteMap("~/sitemap.xml", urlRewriteVideoOld);
            Globals.DeleteUrlList("~/urllist.txt", urlRewriteVideoOld);

            //create db log
            CreateDBLog(null, null, TypeAction.Delete, "Xoá video clip: " + video.Title, video.Description, "", "", "",
                video.IsActive.Value.ToString(), video.IsTop.Value.ToString(), video.MetaKeywords, video.MetaDescription);

            entity.DeleteObject(video);
            entity.SaveChanges();
            //data cache
            Cache.Remove("Video");
            Response.Redirect("VideoClips.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvVideoClip.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    int videoID = int.Parse(((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    udv_Videos video = entity.udv_Videos.Where(vd => vd.VideoID == videoID).FirstOrDefault();
                    if (video != null && video.FileType.Contains("video"))
                    {
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + video.FileURL));
                    }
                    Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_Videos_Folder_MapPath + video.ImageUrl));
                    string urlRewriteVideoOld = Globals.CreateUrlRewriteVideo(ref entity, video.VideoID, true) + DGSFramework.Globals.GetUrlRewriteExtension();
                    Globals.DeleteROR("~/ror.xml", urlRewriteVideoOld);
                    Globals.DeleteSiteMap("~/sitemap.xml", urlRewriteVideoOld);
                    Globals.DeleteUrlList("~/urllist.txt", urlRewriteVideoOld);

                    //create db log
                    CreateDBLog(null, null, TypeAction.Delete, "Xoá video clip: " + video.Title, video.Description, "", "", "",
                        video.IsActive.Value.ToString(), video.IsTop.Value.ToString(), video.MetaKeywords, video.MetaDescription);

                    entity.DeleteObject(video);
                    entity.SaveChanges();
                }
            }
            //data cache
            Cache.Remove("Video");
            Response.Redirect("VideoClips.aspx");
        }

        protected void rdbUploadFile_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbUploadFile.Checked == false)
            {
                //txtURLVideo.Enabled = true;
                txtURLVideo.ReadOnly = false;
                fuVideo.Enabled = false;
                SearchVideos();
            }
            else
            {
                //txtURLVideo.Enabled = false;
                txtURLVideo.ReadOnly = true;
                fuVideo.Enabled = true;
                SearchVideos();
            }
        }

        protected void rdbUploadURL_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbUploadURL.Checked == true)
            {
                //txtURLVideo.Enabled = true;
                txtURLVideo.ReadOnly = false;
                fuVideo.Enabled = false;
                SearchVideos();
            }
            else
            {
                //txtURLVideo.Enabled = false;
                txtURLVideo.ReadOnly = true;
                fuVideo.Enabled = true;
                SearchVideos();
            }
        }

        protected void grvVideoClip_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvVideoClip.ToolTip == "all")
                LoadVideos();
            else
            {
                SearchVideos();
            }
        }

        protected void grvVideoClip_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvVideoClip.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvVideoClip_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvVideoClip.PageIndex = e.NewPageIndex;
            if (grvVideoClip.ToolTip == "all")
                LoadVideos();
            else
            {
                SearchVideos();
            }
        }

        public void SearchVideos()
        {
            var source = entity.udv_Videos.Include("udv_Categories").Select(vd => new { vd.VideoID, vd.Title, vd.Title_en, CateName = vd.udv_Categories.Title, CateID = vd.udv_Categories.CateID, vd.AddedDate, vd.IsActive, vd.DisplayOrder }).OrderBy(vd => vd.DisplayOrder).ThenByDescending(vd => vd.AddedDate).ToList();
            if (txtSearch.Text != "")
            {
                source = source.Where(vd => Globals.RemoveSign4VietnameseString(vd.Title).ToLower().Contains(Globals.RemoveSign4VietnameseString(txtSearch.Text.Trim()).ToLower())).ToList();
            }
            if (ddlCategories2.SelectedValue != "0")
            {
                source = source.Where(vd => vd.CateID == int.Parse(ddlCategories2.SelectedValue)).ToList();
            }
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                source = source.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                source = source.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvVideoClip.DataSource = source;
            grvVideoClip.DataBind();

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvVideoClip.PageIndex = 0;
            grvVideoClip.ToolTip = "search";
            SearchVideos();
        }

        protected void imbEdit_DataBinding(object sender, EventArgs e)
        {
            ImageButton imbEdit = (ImageButton)sender;
            ScriptManager smCurrent = ScriptManager.GetCurrent(Page);
            smCurrent.RegisterPostBackControl(imbEdit);
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
       string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}